package com.woniuxy.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.ResponseResult;
import com.woniuxy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 作者
 * @create 2025-07-01 16:18
 */

@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入loginFilter");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ResponseResult responseResult=null;
        //特殊路径放行
        if (request.getPath().value().contains("/login")) {
            log.info("登录请求，直接放行");
            return chain.filter(exchange);
        }
        log.info("其他请求，验证token");
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.hasLength(token) && JwtUtil.validate(token)) {
            log.info("token有效，直接放行");
            return chain.filter(exchange);
        }else{
            log.info("token无效，拦截");
            responseResult = new ResponseResult(401, "error", "先登录");
            return getVoidMono(responseResult, response);
        }
    }

    private static Mono<Void> getVoidMono(ResponseResult responseResult, ServerHttpResponse response) {
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
        //响应的数据，字符串
        String responseString = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            responseString = objectMapper.writeValueAsString(responseResult);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        //字符串转成字节数组，使用bufferFactory包装
        DataBuffer wrap = response.bufferFactory().wrap(responseString.getBytes());
        //响应数据
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
